﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using SourceCode.Workflow.Client;
using SourceCode.SmartObjects.Client;
using SourceCode.Hosting.Client.BaseAPI;
using System.Security.Principal;
using System.Collections.ObjectModel;
using Core.ExceptionHandling;
//using SourceCode.Workflow.Management;

namespace K2CoreLib
{
    /// <summary>
    /// This is a util of K2 
    /// </summary>
    public class K2Utils
    {
        private static readonly string SERVER = ConfigurationManager.AppSettings.Get("K2ServerName");
        public static readonly string TER_PROCESS_NAME = ConfigurationManager.AppSettings.Get("TerProcessName");
        public static readonly string WK_PROCESS_NAME = ConfigurationManager.AppSettings.Get("WKProcessName");
        public static readonly string TS_PROCESS_NAME = ConfigurationManager.AppSettings.Get("TSProcessName");
        public static readonly string TS_LEAVE_PROCESS_NAME = ConfigurationManager.AppSettings.Get("LeaveRequest");
        public static readonly string TER_PROCESS_EXIT = ConfigurationManager.AppSettings.Get("ExitCheckList");
        public static readonly string RE_Recruitment = ConfigurationManager.AppSettings.Get("Recruitment");
        public static readonly string vHCS_Link = ConfigurationManager.AppSettings.Get("K2AppLink");

        //(empid, workingrecordid, fromhierarchy, tohierarchy, hierarchyid);
        public static int StartWordkingProcess(string sEmpID, string workingrecordid, string fromhierarchy, string tohierarchy, string hierarchyid, 
            string NextApprover, string MailContent, string MailSubject, string EmailDeptOld,string MailContentRequest,string MailSubjectRequest,string EmailRequester
            ,string MailSubject_HR,string MailContent_HR,string MailHR,string MailHRP,string Requester,string ProcessID,string ProcessCode,string version,string sUserRequestFor,
            string ApproveLink,string ViewHistoryLink,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);
            try
            {
                ProcessInstance pi = cnn.CreateProcessInstance(WK_PROCESS_NAME);
                pi.Folio = ProcessCode + ": Staff movement request for "+sUserRequestFor+" (Created by: " + Requester + ")";

                pi.DataFields["EmpID"].Value = sEmpID;//helper.GetNextUser(OFFWORK_TOPAPPROVE, OFFWORK_PROCESS_NAME, RqUser);
                pi.DataFields["WorkingrecordID"].Value = workingrecordid;
                //pi.DataFields["FromHierarchy"].Value = fromhierarchy;
                pi.DataFields["ToHierarchy"].Value = tohierarchy;
                //pi.DataFields["HierarchyId"].Value = hierarchyid;
                pi.DataFields["DeptOld"].Value = NextApprover;
                pi.DataFields["MailContent"].Value = MailContent;
                pi.DataFields["MailDeptOld"].Value = EmailDeptOld;
                pi.DataFields["MailSubject"].Value = MailSubject;
                pi.DataFields["MailRequester"].Value = EmailRequester;
                pi.DataFields["MailSubject_Request"].Value = MailSubjectRequest;
                pi.DataFields["MailContent_Request"].Value = MailContentRequest;
                pi.DataFields["MailSubject_HR"].Value = MailSubject_HR;
                pi.DataFields["MailContent_HR"].Value = MailContent_HR;
                pi.DataFields["MailHR"].Value = MailHR;
                pi.DataFields["MailHRP"].Value = MailHRP;
                pi.DataFields["Requester"].Value = Requester;
                pi.DataFields["ProcessID"].Value = ProcessID;
                pi.DataFields["Version"].Value = version;
                pi.DataFields["ApproveLink"].Value = ApproveLink;
                pi.DataFields["ViewHistoryLink"].Value = ViewHistoryLink;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;
                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);
                int piID = pi.ID;

                //SourceCode.Workflow.Management.
                //SourceCode.Workflow.Management.ProcessInstance pi1 = cnn.OpenProcessInstance(piID);
                //pi

                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }

        public static int StartExitCheckList(string sEmpID,string sRequester, string sDeptHead, string sAccount, string sHROther, string sAFProperty, string sHRProperty, string sITProperty, string sHRTranining,string CountApprove,string ProcessID
            ,string MailRequester,string MailContent_Requester,string MailSubject_Requester
            , string MailDeptHead, string MailAccount, string MailHROther, string MailAFProperty, string MailHRProperty, string MailITProperty, string MailHRTranining,string MailContent_NextApprover,string MailSubject_NextApprover,string EmailOther
            ,string AFOther,string ITOther,string AccounterOther,string MailAFOther,string MailITOther,string MailAccountOther,string processcode,string MailHRBP,string version,string sUserRequestFor
            ,string ApproveLink,string ViewHistoryLink,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);

            try
            {
                ProcessInstance pi = cnn.CreateProcessInstance(TER_PROCESS_EXIT);
                pi.Folio = processcode + ": ExitChecklist request for "+sUserRequestFor+" (Created by: " + sRequester + ")";

                pi.DataFields["ProcessCode"].Value = processcode;
                pi.DataFields["EmpID"].Value = sEmpID;
                pi.DataFields["DeptHead"].Value = sDeptHead;
                pi.DataFields["Accounter"].Value = sAccount;
                pi.DataFields["HROther"].Value = sHROther;
                pi.DataFields["AFProperty"].Value = sAFProperty;
                pi.DataFields["HRProperty"].Value = sHRProperty;
                pi.DataFields["HRTraining"].Value = sHRTranining;
                pi.DataFields["Requester"].Value = sRequester;
                pi.DataFields["AllApprove"].Value = CountApprove;
                pi.DataFields["ITProperty"].Value = sITProperty;
                pi.DataFields["ProcessID"].Value = ProcessID;
                //Gán tham số gửi mail requester
                pi.DataFields["MailRequester"].Value = MailRequester;
                pi.DataFields["MailSubject_Requester"].Value = MailSubject_Requester;
                pi.DataFields["MailContent_Requester"].Value = MailContent_Requester;
                //Gán tham số gửi mail approver
                pi.DataFields["MailDeptHead"].Value = MailDeptHead;
                pi.DataFields["MailAccountor"].Value = MailAccount;
                pi.DataFields["MailHROther"].Value = MailHROther;
                pi.DataFields["MailAFProperty"].Value = MailAFProperty;
                pi.DataFields["MailHRProperty"].Value = MailHRProperty;
                pi.DataFields["MailITProperty"].Value = MailITProperty;
                pi.DataFields["MailHRTraining"].Value = MailHRTranining;
                pi.DataFields["MailSubject_NextApprove"].Value = MailSubject_NextApprover;
                pi.DataFields["MailContent_NextApprove"].Value = MailContent_NextApprover;
                pi.DataFields["EmailOther"].Value = EmailOther;
                pi.DataFields["AFOtherProperty"].Value = AFOther;
                pi.DataFields["ITOtherProperty"].Value = ITOther;
                pi.DataFields["AccounterOther"].Value = AccounterOther;
                pi.DataFields["MailAccountorOther"].Value = MailAccountOther;
                pi.DataFields["MailITOther"].Value = MailITOther;
                pi.DataFields["MailAFOther"].Value = MailAFOther;
                pi.DataFields["MailHRBP"].Value = MailHRBP;
                pi.DataFields["Version"].Value = version;
                pi.DataFields["ApproveLink"].Value = ApproveLink;
                pi.DataFields["ViewHistoryLink"].Value = ViewHistoryLink;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;

                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);
                int piID = pi.ID;

                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }


        public static int StartOTProcess(string sEmpID, string sApprover, string sUserRequest, string sMonthYear, string sOverTimeID, string ProcessID, string ProcessCode
            , string MailApprover, string MailRequester, string viewHistoryOTLink, string approveOTLink, string strContentOT,string version,string sUserRequestFor,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);

            try
            {
                ProcessInstance pi = cnn.CreateProcessInstance(TS_PROCESS_NAME);
                pi.Folio = ProcessCode + ": Overtime request for " + sUserRequestFor + " (Created by: " + sUserRequest + ")";

                pi.DataFields["EmpID"].Value = sEmpID;
                pi.DataFields["Approver"].Value = sApprover;
                pi.DataFields["UserID"].Value = sUserRequest;
                pi.DataFields["MonthYear"].Value = sMonthYear;
                pi.DataFields["OverTimeID"].Value = sOverTimeID;
                pi.DataFields["ProcessID"].Value = ProcessID;
                pi.DataFields["MailApprover"].Value = MailApprover;
                pi.DataFields["Mail_Requester"].Value = MailRequester;
                pi.DataFields["ViewHistoryOTLink"].Value = viewHistoryOTLink;
                pi.DataFields["ApproveOTLink"].Value = approveOTLink;
                pi.DataFields["ContentOT"].Value = strContentOT;
                pi.DataFields["Version"].Value = version;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;

                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);
                int piID = pi.ID;


                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }

        public static int StartLeaveRequestProcess(string sEmpID, float ExceedLeave, string LeaveRecordID, string ApplicationLeaveID,
                                                   string Requester,string FromDate,string ToDate,string ProcessID,string ProcessCode, 
                                                    string approveLink, string viewHistoryLink, string totalDay,string version,string sUserRequestFor,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);
            try
            {

                ProcessInstance pi = cnn.CreateProcessInstance(TS_LEAVE_PROCESS_NAME);
                pi.Folio = ProcessCode + ": Leave request for "+sUserRequestFor+" (Created by: " + Requester + ")";

                pi.DataFields["EmpID"].Value = sEmpID;
                //pi.DataFields["ReportingLine"].Value = sApprover;
                pi.DataFields["ExceedLeave"].Value = ExceedLeave;
                pi.DataFields["LeaveRecordID"].Value = LeaveRecordID;
                pi.DataFields["ApplicationLeaveID"].Value = ApplicationLeaveID;
                pi.DataFields["FromDate"].Value = FromDate;
                pi.DataFields["ToDate"].Value = ToDate;
                pi.DataFields["Requester"].Value = Requester;
                pi.DataFields["TotalDay"].Value = totalDay;
                //pi.DataFields["MailRequester_Content"].Value = MailRequester_Content;
                //pi.DataFields["MailRequester_Subject"].Value = MailRequester_Subject;
                //pi.DataFields["EmailRequester"].Value = EmailRequester;
                //pi.DataFields["MailAdmin_Subject"].Value = MailAdmin_Subject;
                //pi.DataFields["MailAdmin_Content"].Value = MailAdmin_Content;
                //pi.DataFields["MailAdmin"].Value = EmailAdmin;
                //pi.DataFields["MailNextApprover_Subject"].Value = MailNextApprover_Subject;
                //pi.DataFields["MailNextApprover_Content"].Value = MailNextApprover_Content;
                //pi.DataFields["MailReportingLine"].Value = MailNextApprover;
                pi.DataFields["ProcessID"].Value = ProcessID;
                pi.DataFields["ApproveLink"].Value = approveLink;
                pi.DataFields["ViewHistoryLink"].Value = viewHistoryLink;
                pi.DataFields["Version"].Value = version;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;

                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);
                int piID = pi.ID;

                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }
        /// <summary>
        /// Start process cua Termination
        /// </summary>
        /// <param name="sEmpID"></param>
        /// <param name="sHierID"></param>
        /// <param name="NextApproved"></param>
        /// <param name="Leader"></param>
        /// <param name="manager"></param>
        /// <returns></returns>
        public static int StartTerProcess(string sEmpID, string sHierID,string NextApproved,string requester,string LeaveWorkID,string MailContent,string SubjectMail,string MailApprover
                                            ,string MailSubject_Request,string MailContent_Request,string MailRequester,string MailSubject_HR,string MailContent_HR,string MailDeptHead,string MailHRP,string MailCB,string MailHR,string ProcessID,string ProcessCode,string MailHRPLead,string CurrentVersion,string sUserRequestFor
                                            ,string ApproveLink,string ViewHistoryLink,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);

            try
            {
                ProcessInstance pi = cnn.CreateProcessInstance(TER_PROCESS_NAME);

                pi.Folio = ProcessCode + ": Termination request for "+sUserRequestFor+" (Created by: " + requester + ")";

                pi.DataFields["EmpID"].Value = sEmpID;//helper.GetNextUser(OFFWORK_TOPAPPROVE, OFFWORK_PROCESS_NAME, RqUser);
                pi.DataFields["HierID"].Value = sHierID;
                pi.DataFields["DirectSuperior"].Value = NextApproved;
                pi.DataFields["Requester"].Value = requester;
                pi.DataFields["LeaveWorkID"].Value = LeaveWorkID;
                pi.DataFields["ContentMail"].Value =  MailContent;
                pi.DataFields["SubjectMail"].Value = SubjectMail;
                pi.DataFields["ProcessID"].Value = ProcessID;

                //Gán thông tin gửi mail request
                pi.DataFields["MailRequester"].Value = MailRequester;
                pi.DataFields["MailSubject_Request"].Value = MailSubject_Request;
                pi.DataFields["MailContent_Request"].Value = MailContent_Request;
                //

                //Gán thông tin gửi mail đến DeptHead,HRP,CB khi creator submitted
                pi.DataFields["MailDeptHead"].Value = MailDeptHead;
                pi.DataFields["MailHRP"].Value = MailHRP;
                pi.DataFields["MailDirect"].Value = MailApprover;
                pi.DataFields["MailCB"].Value = MailCB;
                pi.DataFields["MailSubject_HR"].Value = MailSubject_HR;
                pi.DataFields["MailContent_HR"].Value = MailContent_HR;
                pi.DataFields["MailHR"].Value = MailHR;
                pi.DataFields["MailHRPLead"].Value = MailHRPLead;
                pi.DataFields["Version"].Value = CurrentVersion;
                pi.DataFields["ApproveLink"].Value = ApproveLink;
                pi.DataFields["ViewHistoryLink"].Value = ViewHistoryLink;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;
                //

                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);

                int piID = pi.ID;

                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }


        /// <summary>
        /// Start process RE
        /// </summary>
        /// <param name="sEmpID"></param>
        /// <param name="sHierID"></param>
        /// <param name="NextApproved"></param>
        /// <param name="Leader"></param>
        /// <param name="manager"></param>
        /// <returns></returns>
        public static int StartReProcess(string Requester,string Approver,string ProcessID,string ProcessCode,string RequestID,
            string MailContent_HRP, string MailSubject_HRP, string MailHRP, string MailRequester, string DeptID, string DivID, string DeptName, string DivName, string MailContent_Request, string MailSubject_Request,string MailRequestFor,string MailRRM,string MailRRMGroup,string version,string sUserRequestFor
            ,string ApproveLink,string ViewHistoryLink,string ExpireDay,string ExpireAlert)
        {
            // Connect to K2 host Server
            Connection cnn = new Connection();
            cnn.Open(SERVER);

            try
            {
                ProcessInstance pi = cnn.CreateProcessInstance(RE_Recruitment);

                pi.Folio = ProcessCode + ": Recruitment request for "+(string.IsNullOrEmpty(sUserRequestFor)?Requester:sUserRequestFor)+" (Created by: " + Requester + ")";

                pi.DataFields["HRBP"].Value = Approver;
                pi.DataFields["ProcessID"].Value = ProcessID;
                pi.DataFields["Requester"].Value = Requester;
                pi.DataFields["RequestID"].Value = RequestID;
                pi.DataFields["MailHRP"].Value = MailHRP;
                pi.DataFields["MailRequester"].Value = MailRequester;
                pi.DataFields["MailRequestFor"].Value = MailRequestFor;
                pi.DataFields["MailSubject_ToHRP"].Value = MailSubject_HRP;
                pi.DataFields["MailContent_ToHRP"].Value = MailContent_HRP;
                pi.DataFields["DeptID"].Value = DeptID;
                pi.DataFields["DivID"].Value = DivID;
                pi.DataFields["DeptName"].Value = DeptName;
                pi.DataFields["DivName"].Value = DivName;
                pi.DataFields["MailSubject_Request"].Value = MailSubject_Request;
                pi.DataFields["MailContent_Request"].Value = MailContent_Request;
                pi.DataFields["MailRRM"].Value = MailRRM;
                pi.DataFields["MailRRMGroup"].Value = MailRRMGroup;
                pi.DataFields["Version"].Value = version;
                pi.DataFields["ApproveLink"].Value = ApproveLink;
                pi.DataFields["ViewHistoryLink"].Value = ViewHistoryLink;
                pi.DataFields["ExpireDay"].Value = ExpireDay;
                pi.DataFields["ExpireAlert"].Value = ExpireAlert;

                //Gán đường link vào K2
                pi.DataFields["vHCSLink"].Value = vHCS_Link;

                // Start Process Instance
                cnn.StartProcessInstance(pi);

                int piID = pi.ID;

                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }
        /// <summary>
        /// Hàm thực hiện Submit len eForm
        /// </summary>
        /// <param name="Requester"></param>
        /// <param name="DomainAccount"></param>
        /// <param name="TypeID"></param>
        /// <param name="DateRequired"></param>
        /// <param name="LinkContent"></param>
        /// <param name="LinkFLow"></param>
        /// <param name="status">0: In process, 1: Complete, 2: Rework, 3:Reject</param>
        public static string submit2EForm(string Requester, string DomainAccount, int TypeID, string DateRequired, string LinkContent, string status,string RequestFor)
        { 
            SmartObjectClientServer server = new SmartObjectClientServer();
                   
            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;
                   
                //Create the connection
                server.CreateConnection();
                server.Connection.Open(cb.ToString());
                   
                //Get the Process SmartObject definition 
                SmartObject process = server.GetSmartObject("Process");
                   
                //Set properties
                process.Properties["Requester"].Value = Requester;
                process.Properties["DomainAccount"].Value = DomainAccount;
                //process.Properties["Group"].Value = ""; //Neu co
                process.Properties["TypeID"].Value = TypeID.ToString();
                process.Properties["DateRequest"].Value = DateTime.Today.ToString();
                process.Properties["DateRequired"].Value = DateRequired;
                process.Properties["RequestFor"].Value = RequestFor; //Neu co'
                process.Properties["LinkContent"].Value = LinkContent;
                
                process.Properties["Status"].Value = status; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                //process.Properties["K2ProcessID"].Value = procid.ToString();
                
                //Create the SmartObject
                process.MethodToExecute = "Create";
                SmartObject history= server.ExecuteScalar(process);
                process.MethodToExecute = "Load";
                process.Properties["ID"].Value = history.Properties["ID"].Value.ToString();
                SmartObject processcode = server.ExecuteScalar(process);

                return  processcode.Properties["Code"].Value.ToString()+","+ history.Properties["ID"].Value.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
        }

        /// <summary>
        /// Hàm trả về tình trạng trên eform của process
        /// </summary>
        /// <param name="Requester"></param>
        /// <param name="DomainAccount"></param>
        /// <param name="TypeID"></param>
        /// <param name="DateRequired"></param>
        /// <param name="LinkContent"></param>
        /// <param name="LinkFLow"></param>
        /// return status 0: In process, 1: Complete, 2: Rework, 3:Reject</param>
        public static string ReturnStatus(string processid)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();

            try
            {
                if (!string.IsNullOrEmpty(processid))
                {
                    //Make the server connection
                    SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                    cb.Host = SERVER;
                    cb.Port = 5555;
                    cb.Integrated = true;
                    cb.IsPrimaryLogin = true;

                    //Create the connection
                    server.CreateConnection();
                    server.Connection.Open(cb.ToString());

                    //Get the Process SmartObject definition 
                    SmartObject process = server.GetSmartObject("Process");

                    //Set properties
                    process.Properties["ID"].Value = processid;
                    process.MethodToExecute = "Load";

                    SmartObject processcode = server.ExecuteScalar(process);

                    return processcode.Properties["Status"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
            return "";
        }

        /// <summary>
        /// Hàm trả về người approver tiếp theo trên process
        /// </summary>
        /// <param name="Requester"></param>
        /// <param name="DomainAccount"></param>
        /// <param name="TypeID"></param>
        /// <param name="DateRequired"></param>
        /// <param name="LinkContent"></param>
        /// <param name="LinkFLow"></param>
        /// return status 0: In process, 1: Complete, 2: Rework, 3:Reject</param>
        public static string ReturnNextApprover(string processid)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();

            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;

                //Create the connection
                server.CreateConnection();
                server.Connection.Open(cb.ToString());

                //Get the Process SmartObject definition 
                SmartObject process = server.GetSmartObject("Process");

                //Set properties
                process.Properties["ID"].Value = processid;
                process.MethodToExecute = "Load";

                SmartObject processcode = server.ExecuteScalar(process);

                return processcode.Properties["NextApprover"].Value.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
        }

        /// <summary>
        /// Hàm thực hiện Submit len eForm
        /// </summary>
        /// <param name="Requester"></param>
        /// <param name="DomainAccount"></param>
        /// <param name="TypeID"></param>
        /// <param name="DateRequired"></param>
        /// <param name="LinkContent"></param>
        /// <param name="LinkFLow"></param>
        /// <param name="status">0: In process, 1: Complete, 2: Rework, 3:Reject</param>
        public static string Update2EForm(string status, string procid,string processinstantid)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();

            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;

                //Create the connection
                server.CreateConnection();
                server.Connection.Open(cb.ToString());

                //Get the Process SmartObject definition 
                SmartObject process = server.GetSmartObject("Process");
                //Set properties
                process.Properties["ID"].Value = procid;
                process.Properties["Status"].Value = status; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                process.Properties["LinkFLow"].Value = GetFlowLink(server) + processinstantid;
                //process.Properties["K2ProcessID"].Value = procid.ToString();

                //Create the SmartObject
                process.MethodToExecute = "Save";
                SmartObject history = server.ExecuteScalar(process);
                return "";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
        }

        /// <summary>
        /// Hàm thực hiện Submit len eForm
        /// </summary>
        /// <param name="Requester"></param>
        /// <param name="DomainAccount"></param>
        /// <param name="TypeID"></param>
        /// <param name="DateRequired"></param>
        /// <param name="LinkContent"></param>
        /// <param name="LinkFLow"></param>
        /// <param name="status">0: In process, 1: Complete, 2: Rework, 3:Reject</param>
        public static string Update2EForm_LinkContent(string procid, string LinkContent)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();

            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;

                //Create the connection
                server.CreateConnection();
                server.Connection.Open(cb.ToString());

                //Get the Process SmartObject definition 
                SmartObject process = server.GetSmartObject("Process");
                //Set properties
                process.Properties["ID"].Value = procid;
                process.Properties["LinkContent"].Value = LinkContent; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                //process.Properties["K2ProcessID"].Value = procid.ToString();

                //Create the SmartObject
                process.MethodToExecute = "Save";
                SmartObject history = server.ExecuteScalar(process);
                return "";
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
        }

        public static string GetFlowLink(SmartObjectClientServer server)
        {
            try
            {
                //Get the Process SmartObject definition 
                SmartObject config = server.GetSmartObject("Config");
                config.Properties["Name"].Value = "FlowLink";

                config.MethodToExecute="GetList";
                SmartObjectList Result_List = server.ExecuteList(config);
                //Write out 
                foreach (SmartObject Result in Result_List.SmartObjectsList)
                {
                    foreach (SmartProperty property in Result.Properties)
                    {
                        if (property.Name == "Value")
                            return property.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return "";
        }

        public static void InsertHistoryComment(string eformid, string DomainAccount)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();
            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;

                //Create the connection
                server.CreateConnection();
                server.Connection.Open(cb.ToString());

                SmartObject history = server.GetSmartObject("HistoryComment");
                history.Properties["RequestID"].Value = eformid;
                history.Properties["DomainAccount"].Value = DomainAccount;
                history.Properties["Date"].Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                history.Properties["SignatureCaption"].Value = "Approver";

                history.MethodToExecute = "Create";
                server.ExecuteScalar(history);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            }
        }

        public Collection<ActionItem> GetActions(string sn, string sharedUser)
        {
            Collection<ActionItem> lstActions = new Collection<ActionItem>();
            // Init connection
            Connection conn = new Connection();
            conn.Open(SERVER);
            try
            {
                WorklistItem workListItem = GetWorklistItem(conn, sn, sharedUser);
                foreach (SourceCode.Workflow.Client.Action act in workListItem.Actions)
                {
                    ActionItem item = new ActionItem();
                    item.Name = act.Name;
                    item.Value = act.Name;
                    lstActions.Add(item);
                }
                return lstActions;
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

        /// <summary>
        /// Lấy Process ID để ở Eform
        /// </summary>
        /// <param name="ProcessName">Tên Process</param>
        /// <returns></returns>
        public static int GetTypeIDProcessFromEfrom(string ProcessName)
        {
            SmartObjectClientServer server = new SmartObjectClientServer();
                   
            try
            {
                //Make the server connection
                SCConnectionStringBuilder cb = new SCConnectionStringBuilder();
                cb.Host = SERVER;
                cb.Port = 5555;
                cb.Integrated = true;
                cb.IsPrimaryLogin = true;
                server.CreateConnection();
                server.Connection.Open(cb.ToString());
                   
                //Get a list of Process type from Process Name
                SmartObject opportunity = server.GetSmartObject("ProcessType");
                
                //Set properties
                opportunity.Properties["ProcessName"].Value = ProcessName;// "HR_TerminationRequest";
                
                //Get the SmartObjects
                opportunity.MethodToExecute = "GetList";
                SmartObjectList opportunities = server.ExecuteList(opportunity);
                
                //Write out 
                foreach (SmartObject companyOpportunity in opportunities.SmartObjectsList)
                {
                    foreach (SmartProperty property in companyOpportunity.Properties)
                    {
                        if (property.Name == "ID")
                            return Convert.ToInt16(property.Value);
                        
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                server.Connection.Close();
            } 
            return 0;
        }

        /// <summary>
        /// DungN2
        /// Lấy Name activity đang hiện hành
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        public static string GetActivityName(string sn, string sharedUser)
        {
            try
            {
                // Init connection
                Connection conn = new Connection();
                conn.Open(SERVER);

                WorklistItem wi = GetWorklistItem(conn, sn, sharedUser);
                return wi.ActivityInstanceDestination.Name;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string GetDataField(string sn, string FieldName, string sharedUser)
        {
            try
            {
                // Init connection
                Connection conn = new Connection();
                conn.Open(SERVER);

                WorklistItem wi = GetWorklistItem(conn, sn, sharedUser);
                string value = "";
                try
                {
                    if (wi.ProcessInstance.DataFields[FieldName] != null)
                    {
                        value = wi.ProcessInstance.DataFields[FieldName].Value.ToString();
                    }
                }
                catch { }

                conn.Close();
                return value;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void SetDataField(string sn, string DataFieldName, string value, string sharedUser)
        {
            try
            {
                // Init connection
                Connection conn = new Connection();
                conn.Open(SERVER);

                WorklistItem wi = GetWorklistItem(conn, sn, sharedUser);
                wi.ProcessInstance.DataFields[DataFieldName].Value = value;

                conn.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static WorklistItem GetWorklistItem(Connection conn, string sn, string shareUser = null, string managerUser = null)
        {
            try
            {
                WorklistItem workListItem = null;
                shareUser = shareUser != null ? shareUser : string.Empty;
                managerUser = managerUser != null ? managerUser : string.Empty;
                // Check if worklist item is for normal user
                if ((shareUser == string.Empty) && (managerUser == string.Empty))
                {
                    workListItem = conn.OpenWorklistItem(sn);
                }
                // Check if worklist item is for Out-Of-Office shared user
                if ((shareUser != string.Empty) && (managerUser == string.Empty))
                {
                    workListItem = conn.OpenSharedWorklistItem(shareUser,managerUser,sn);
                }

                return workListItem;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static WorklistItem GetWorklistItem(string sn, string shareUser, string managerUser = null)
        {
            try
            {
                // Init connection
                Connection conn = new Connection();
                conn.Open(SERVER);

                WorklistItem workListItem = null;
                shareUser = !string.IsNullOrEmpty(shareUser) ? shareUser : string.Empty;
                managerUser = managerUser != null ? managerUser : string.Empty;
                // Check if worklist item is for normal user
                if ((shareUser == string.Empty) && (managerUser == string.Empty))
                {
                    workListItem = conn.OpenWorklistItem(sn);
                }
                // Check if worklist item is for Out-Of-Office shared user
                if ((shareUser != string.Empty) && (managerUser == string.Empty))
                {
                    workListItem = conn.OpenSharedWorklistItem(shareUser, managerUser, sn);
                }

                return workListItem;
                conn.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void ActionExecute(string sn, string action, string sharedUser, object[] parms = null)
        {
            try
            {
                Connection conn = new Connection();
                conn.Open(SERVER);

                WorklistItem wi = GetWorklistItem(conn, sn, sharedUser);

                ProcessInstance pi = wi.ProcessInstance;

                if (parms != null && parms.Length > 0)
                {
                    // NOTE: Processes a name/value pair at each iteration
                    for (int i = 0; i < parms.Length; i += 2)
                    {
                        string name = parms[i].ToString();

                        // No empty strings to the database
                        if (parms[i + 1] is string && (string)parms[i + 1] == "")
                            parms[i + 1] = null;

                        try
                        {
                            if (pi.DataFields[name] != null)
                            {
                                pi.DataFields[name].Value = parms[i + 1];
                            }
                        }
                        catch { }
                    }
                }

                wi.Actions[action].Execute();

                conn.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static int TestK2()
        {
            try
            {
                // Connect to K2 host Server
                Connection cnn = new Connection();
                cnn.Open(SERVER);

                ProcessInstance pi = cnn.CreateProcessInstance(TS_LEAVE_PROCESS_NAME);
                pi.Folio = "Test";

                // Start Process Instance
                cnn.StartProcessInstance(pi);
                int piID = pi.ID;

                cnn.Close();
                return piID;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string GetParaUrl(string currurl)
        {
            string parms = string.Empty;
            // Check to make sure some query string variables
            // exist and if not add some and redirect.
            int iqs = currurl.IndexOf('?');
            // If query string variables exist, put them in a string.
            if (iqs >= 0)
            {
                parms = (iqs < currurl.Length - 1) ? currurl.Substring(iqs + 1) : String.Empty;
            }
            return parms;
        }
       
    }
    public class ActionItem
    {
        private string _Name;
        private string _Value;
        public string Name { get { return _Name; } set { _Name = value; } }
        public string Value { get { return _Value; } set { _Value = value; } }
    }
}